/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.sourceforge.bookscanwizard.config;

import java.awt.image.RenderedImage;
import java.text.DecimalFormat;
import javax.media.jai.Histogram;
import javax.media.jai.JAI;
import net.sourceforge.bookscanwizard.op.ImageStatistics;

/**
 * Maximizes the color range while keeping the mid range set at the current
 * value.  This should be done when the brightness has already been normalized
 */
public class ConfigBalancedAutoLevels {
    private DecimalFormat formatter = new DecimalFormat("#.#");

    public String getConfig(RenderedImage img) {
        StringBuilder retVal = new StringBuilder("Levels = ");
        StringBuilder gamma = new StringBuilder("Gamma = ");
        Histogram histogram =
           (Histogram)JAI.create("histogram", img).getProperty("histogram");
        double[] blackLevels = histogram.getPTileThreshold(.01);
        double[] whiteLevels = histogram.getPTileThreshold(.99);
        for (int i=0; i < blackLevels.length; i++) {
            double blackLevel = blackLevels[i] * 100D / 255D;
            retVal.append(formatter.format(blackLevel)).append(",");
            double whiteLevel = whiteLevels[i] * 100D / 255D;
            retVal.append(formatter.format(whiteLevel)).append(", ");

            double scale = 255D / (whiteLevel - blackLevel);
            double offset = 255D * blackLevel / (blackLevel - whiteLevel);
            double newGray = offset + ImageStatistics.GRAY_STANDARD * scale;
            gamma.append(newGray).append(", ");
        }
        retVal.setLength(retVal.length() - 2);
        retVal.append("\n");
        gamma.setLength(gamma.length() - 2);
        retVal.append(gamma);
        return retVal.toString();
    }
}
